package com.hbnu.net;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * 需求：从键盘录入数据发送出去
 *
 * @author kittychen
 * @since 2025-10-28 16:37
 */
public class UdpSendDemo02 {

    public static void main(String[] args) {
        DatagramSocket datagramSocket = null;

        try {
            datagramSocket = new DatagramSocket(1234);

            // 获取键盘数据
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                if ("bye".equalsIgnoreCase(line)) {
                    break;
                }
                byte[] data = line.getBytes();
                DatagramPacket datagramPacket = new DatagramPacket(data, data.length,
                        InetAddress.getByName("127.0.0.1"), 8888);

                datagramSocket.send(datagramPacket);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (datagramSocket != null) {
                datagramSocket.close();
            }
        }
    }
}
